<template>
  <t-dialog
    header="提取订单商品明细"
    width="90%"
    :visible="showDialog"
    @confirm="handleConfirm"
    @close="handleCancel"
    @cancel="handleCancel"
    preventScrollThrough
    mode="full-screen"
  >
    <t-loading :loading="pageData.loading" text="正在载入数据">
      <div style="overflow: scroll; height: 75vh" v-if="!pageData.loading">
        <FormInfo>
          <template #left>选择订单信息</template>
          <template #content>
            <t-space direction="vertical" style="width: 100%">
              <t-form class="crud-form" :data="null">
                <t-space direction="vertical" style="width: 100%">
                  <t-row>
                    <t-col :span="4">
                      <t-form-item :labelWidth="90" label="客户" name="customerMainName">
                        <InputSelect
                          :value="pageData.order.filterValue.customerMainName"
                          @onClick="pageData.customer.show = true"
                        />
                      </t-form-item>
                    </t-col>
                    <t-col :span="4">
                      <t-form-item :labelWidth="90" label="订单号" name="orderNo">
                        <t-input v-model="pageData.order.filterValue.orderNo" />
                      </t-form-item>
                    </t-col>
                    <t-col :span="4">
                      <t-form-item :labelWidth="90" label="订单名称" name="orderName">
                        <t-input v-model="pageData.order.filterValue.orderName" />
                      </t-form-item>
                    </t-col>
                  </t-row>

                  <div class="crud-form__operations">
                    <t-button theme="primary" @click="handleOrderFilterChange">查询</t-button>
                    <t-button ttheme="warning" @click="handleOrderFilterReset">重置</t-button>
                  </div>
                </t-space>
              </t-form>

              <t-table
                row-key="id"
                activeRowType="single"
                :data="pageData.order.data.records"
                :columns="orderColumns"
                :pagination="pageData.order.pagination"
                @page-change="handleOrderPageChange"
                table-layout="fixed"
                max-height="310px"
                row-selection-type="single"
                select-on-row-click
                :row-selection-allow-uncheck="true"
                tableContentWidth="100%"
                bordered
                lazy-load
              >
                <template #operation="{ row }">
                  <t-link variant="text" theme="primary" @click="handleOrderSelect(row)">选择</t-link>
                </template>
              </t-table>
            </t-space>
          </template>
        </FormInfo>
        <FormInfo>
          <template #left>订单对应商品信息</template>
          <template #content>
            <t-table
              row-key="id"
              activeRowType="single"
              :data="pageData.targetExpressGoods.data"
              :columns="targetExpressGoodsColumn"
              table-layout="fixed"
              max-height="300px"
              row-selection-type="single"
              select-on-row-click
              :row-selection-allow-uncheck="true"
              tableContentWidth="100%"
              bordered
              lazy-load
            />
          </template>
        </FormInfo>
      </div>
    </t-loading>
  </t-dialog>

  <SelectTable
    v-if="pageData.customer.show"
    title="选择客户"
    :showDialog="pageData.customer.show"
    :loading="pageData.customer.loading"
    width="60vw"
    rowSelectionType="single"
    :tableData="pageData.customer.data.records"
    :columns="customerColumns"
    @onConfirm="handleCustomerConfirm"
    @onCancel="handleCustomerClose"
    :pagination="pageData.customer.pagination"
    @page-change="handleCustomerPageChange"
    :filter-value="pageData.customer.filterValue"
    @filter-change="handleCustomerFilterChange"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw, watch } from "vue";
import { MessagePlugin, type TableProps } from "tdesign-vue-next";

// TS 类型文件
import type { ICrudDataPagination, ICrudTableDataPage, ISelectTableGroups } from "@/types";

// 工具函数
import { v4 as uuidv4 } from "uuid";
import dayjs from "dayjs";
import { newPrecision } from "@/utils/tools";

// 常量
import { PAGINATION_VALUE } from "@/common/constants";

// API
import { getOrderList } from "@/api/order";
import { getCustomerList } from "@/api/cas";

// 业务数据
import { tableColumns as customerColumns } from "@/pages/Dashboard/CAS/Customer/components/columns";

defineProps(["width", "showDialog"]);

const emits = defineEmits(["onConfirm", "onClose"]);

const pageData = reactive({
  loading: false,
  customer: {
    show: false,
    loading: false,
    data: {},
    filterValue: {},
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    }
  } as ISelectTableGroups,
  order: {
    data: {} as ICrudTableDataPage,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    } as ICrudDataPagination,
    filterValue: {} as Record<string, any>
  },
  targetExpressGoods: {
    data: []
  },
  emptyProductData: {
    productId: "",
    hasDeleted: 0,
    customsId: "",
    kgs: 0,
    gws: 0,
    originCountry: "",
    bulk: 0,
    expressCountry: "",
    freeTax: "",
    decElement: "",
    expressNumber: 0,
    chinaSupplied: "",
    id: "",
    expressId: "",
    productEngName: "",
    specification: "",
    unit: ""
  }
});

const orderColumns = ref<TableProps["columns"]>([
  {
    colKey: "serial-number",
    title: "序号",
    align: "center",
    width: 70,
    fixed: "left"
  },
  {
    colKey: "orderId",
    title: "订单号",
    width: 200
  },
  {
    colKey: "orderCustomerId",
    title: "客户名称",
    width: 220,
    cell: (h, { row }) => {
      return row.customer?.name;
    }
  },
  {
    colKey: "orderName",
    title: "订单名称",
    width: 220
  },
  {
    colKey: "deliveryTerm",
    title: "交货期限",
    width: 220,
    cell: (h, { row }) => {
      return dayjs(row.deliveryTerm).format("YYYY-MM-DD HH:mm:ss");
    }
  },
  {
    colKey: "loadPortId",
    title: "装运口岸",
    width: 220,
    cell: (h, { row }) => {
      return row.loadPort?.portName;
    }
  },
  {
    colKey: "unloadPortId",
    title: "运抵港",
    width: 220,
    cell: (h, { row }) => {
      return row.unloadPort?.portName;
    }
  },
  { colKey: "operation", title: "操作", width: 150, fixed: "right" }
]);

const getOrderData = async () => {
  pageData.loading = true;
  const resultData = await getOrderList(
    pageData.order.pagination.current,
    pageData.order.pagination.pageSize,
    pageData.order.filterValue
  );

  if (resultData.code === 200) {
    pageData.order.data = resultData.data;
    pageData.order.pagination.total = resultData.data.total;
    pageData.order.pagination.current = resultData.data.current;
    pageData.order.pagination.pageSize = resultData.data.size;
    pageData.loading = false;
  }
};

const targetExpressGoodsColumn = ref<TableProps["columns"]>([
  {
    colKey: "serial-number",
    title: "序号",
    align: "center",
    width: 70,
    fixed: "left"
  },
  {
    colKey: "productChnName",
    title: "产品中文名",
    width: 200
  },
  {
    colKey: "productEngName",
    title: "产品英文名",
    width: 200
  },
  {
    colKey: "number",
    title: "数量",
    width: 250
  },
  {
    colKey: "specification",
    title: "规格/型号",
    width: 200
  },
  {
    colKey: "maxOverNum",
    title: "最大溢出数（5%）",
    width: 200
  },
  {
    colKey: "hadExpressNumber",
    title: "已出运数量",
    width: 200
  },
  {
    colKey: "expressNumber",
    title: "本次出运数量",
    width: 200,
    cell: (h, { row }) => {
      return <t-input-number theme="column" decimalPlaces={0} v-model={row.expressNumber} />;
    }
  }
]);

const getCustomerData = async () => {
  pageData.customer.loading = true;
  const resultData = await getCustomerList(
    pageData.customer.pagination.current,
    pageData.customer.pagination.pageSize,
    pageData.customer.filterValue
  );

  if (resultData.code === 200) {
    pageData.customer.data = resultData.data;
    pageData.customer.pagination.total = resultData.data.total;
    pageData.customer.pagination.current = resultData.data.current;
    pageData.customer.pagination.pageSize = resultData.data.size;
    pageData.customer.loading = false;
  }
};

const handleCustomerPageChange = (pageInfo: Record<string, any>) => {
  pageData.customer.pagination.pageSize = pageInfo.pageSize;
  pageData.customer.pagination.current = pageInfo.current;
  getCustomerData();
};

const handleCustomerFilterChange = (filters: Record<string, any>) => {
  pageData.customer.filterValue = filters;
  pageData.customer.pagination = structuredClone(PAGINATION_VALUE);
  getCustomerData();
};

const handleCustomerConfirm = (e: Record<string, any>) => {
  pageData.order.filterValue.customerId = e.options.currentRowData.id;
  pageData.order.filterValue.customerMainName = e.options.currentRowData.name;
  pageData.customer.show = false;
};

const handleCustomerClose = () => {
  pageData.customer.show = false;
};

const handleOrderSelect = (row: Record<string, any>) => {
  if (row.products === null || row.products.length === 0) {
    MessagePlugin.warning("订单内无商品，无法添加！");
    return;
  }
  const targetExpressGoods = row.products.map((item: Record<string, any>) => {
    return {
      productId: item.id,
      hasDeleted: 0,
      customsId: "",
      kgs: 0,
      gws: 0,
      originCountry: "",
      bulk: 0,
      expressCountry: "",
      freeTax: "",
      decElement: "",
      hadExpressNumber: item.expressNumTotal,
      expressNumber: 0,
      chinaSupplied: "",
      id: "",
      localUUID: uuidv4(),
      expressId: "",
      productChnName: item.name,
      productEngName: item.englishName,
      specification: item.specification,
      unit: item.unit,
      maxOverNum: newPrecision(item.number * 1.05, 0),
      orderId: row.id,
      customerId: row.orderCustomerId,
      number: item.number
    };
  });
  pageData.targetExpressGoods.data = targetExpressGoods;
};

const handleOrderPageChange = (pageInfo: Record<string, any>) => {
  pageData.order.pagination.pageSize = pageInfo.pageSize;
  pageData.order.pagination.current = pageInfo.current;
};

const handleOrderFilterChange = () => {
  pageData.order.pagination = structuredClone(PAGINATION_VALUE);
  getOrderData();
};

const handleOrderFilterReset = () => {
  pageData.order.filterValue = {};
  pageData.order.pagination = structuredClone(PAGINATION_VALUE);
  getOrderData();
};

watch(
  () => pageData.targetExpressGoods.data,
  (newVal) => {
    const index = newVal.findIndex(
      (item: Record<string, any>) => item.maxOverNum - item.hadExpressNumber < item.expressNumber
    );
    if (index !== -1) {
      MessagePlugin.warning("本次出运数量超过最大限制。");
    }
  },
  {
    deep: true,
    flush: "post"
  }
);

const handleCancel = () => {
  emits("onClose", "cancel");
};

const handleConfirm = () => {
  const rawData = toRaw(pageData.targetExpressGoods.data);
  emits("onConfirm", structuredClone(rawData));
};

getOrderData();
getCustomerData();
</script>
